<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8" >
            <a-form-model-item label="物料描述" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialDesc">
              <j-popup
                v-model="model.materialDesc"
                field="materialDesc"
                org-fields="material_id,material_desc"
                dest-fields="materialId,materialDesc"
                code="bom_main_material_pop"
                @input="mainMaterialPopupCallback" placeholder="请选择商品"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="工厂" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="factory">
              <j-dict-select-tag type="list" v-model="model.factory" dictCode="mdm_factory,factory_name,id" placeholder="请选择工厂" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="生效日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="effectiveDate">
              <j-date placeholder="请选择生效日期" v-model="model.effectiveDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="BOM项目" :key="refKeys[0]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[0]"
          :loading="mdmBomDetailTable.loading"
          :columns="mdmBomDetailTable.columns"
          :dataSource="mdmBomDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"
          @added = "addRowCallback">
          <div slot="buttonBefore" >
            <div class="action-button">
              <a-button slot="buttonBefore" type="primary" icon="plus" @click="handleClickBatchAdd" :disabled="formDisabled">批量新增</a-button>
              <span class="gap"></span>
            </div>
          </div>
        </j-editable-table>
        <j-popup-onl-report
          ref="jPopupOnlReport"
          code="bom_detail_material_pop"
          multi="true"
          :jEditableParam = "jEditableParam"
          @ok="batchAddPopupCallback"
        />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

  import { getAction } from '@/api/manage'
  import { FormTypes,getRefPromise,VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
  import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
  import { validateDuplicateValue } from '@/utils/util'
  import moment from "moment";

  export default {
    name: 'MdmBomForm',
    mixins: [JEditableTableModelMixin],
    components: {
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        model:{
          effectiveDate: moment(new Date()).format('YYYY-MM-DD'),
        },
        jEditableParam:{ jEditableInstance: null, jEditableColName: 'materialId', paramColName: 'materialIdList'},
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
           materialDesc: [
              { required: true, message: '请选择商品!'},
           ],
          factory: [
            { required: true, message: '请选择工厂!'},
          ],
        },
        mdmBomDetailAddIdList: [],
        refKeys: ['mdmBomDetail', ],
        tableKeys:['mdmBomDetail', ],
        activeKey: 'mdmBomDetail',
        // bom明细
        mdmBomDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '物料描述',
              key: 'materialDesc',
              type: FormTypes.popup,
              popupCode: 'bom_detail_material_pop',
              orgFields: 'material_id,material_code,material_desc,material_unit_code,material_type_id',
              destFields: 'materialId,materialCode,materialDesc,materialUnitCode,materialTypeId',
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              jEditableParam: { jEditableInstance: null, jEditableColName: 'materialId', paramColName: 'materialIdList'},
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '组件数量',
              key: 'partQty',
              type: FormTypes.inputNumber,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '单位',
              key: 'materialUnitCode',
              type: FormTypes.sel_search,
              dictCode:"mdm_unit,unit_name,unit_code",
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '损耗率',
              key: 'lossRate',
              type: FormTypes.input,
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '项目文本',
              key: 'projectNote',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '仓储地点',
              key: 'storageLocation',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '用途',
              key: 'bomUseType',
              type: FormTypes.select,
              dictCode:"mdm_use_type",
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '消耗方式',
              key: 'consumeType',
              type: FormTypes.select,
              dictCode:"mdm_consume_type",
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '生效日期',
              key: 'effectiveDate',
              type: FormTypes.date,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue: moment(new Date()).format('YYYY-MM-DD'),
            },
            {
              title: '失效日期',
              key: 'expiryDate',
              type: FormTypes.date,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue: '9999-12-31',
            },
            {
              title: '版本编号',
              key: 'versionNum',
              type: FormTypes.input,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '工位编号',
              key: 'stationNum',
              type: FormTypes.input,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: 'materialId',
              key: 'materialId',
              type:"hidden"
            },
            {
              title: 'materialCode',
              key: 'materialCode',
              type:"hidden"
            },
            {
              title: 'materialTypeId',
              key: 'materialTypeId',
              type: "hidden"
            },
          ]
        },
        url: {
          add: "/mdm/bom/add",
          edit: "/mdm/bom/edit",
          queryById: "/mdm/bom/queryById",
          mdmBomDetail: {
            list: '/mdm/bom/queryMdmBomDetailByMainId'
          },
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
      tableValues(){
        let materialIdList = '';
        this.$refs[this.refKeys[0]].getValues((error, values) => {
          if (error === 0) {
            if(values && values.length>0){
              for(let i=0; i<values.length; i++){
                materialIdList = materialIdList  + values[i]['materialId'] + ','
              }
            }
          }
        })
        return materialIdList;
      },
    },
    created () {
    },
    methods: {
      addBefore(){
        this.mdmBomDetailTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.mdmBomDetail.list, params, this.mdmBomDetailTable)
        }
      },
      //校验所有一对一子表表单
      validateSubForm(allValues){
          return new Promise((resolve,reject)=>{
            Promise.all([
            ]).then(() => {
              resolve(allValues)
            }).catch(e => {
              if (e.error === VALIDATE_NO_PASSED) {
                // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
              } else {
                console.error(e)
              }
            })
          })
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          mdmBomDetailList: allValues.tablesValue[0].values,
          mdmBomDetailDeleteIdList: allValues.tablesValue[0].deleteIds,
          mdmBomDetailAddIdList: this.mdmBomDetailAddIdList,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
     mainMaterialPopupCallback(value,row){
       this.model = Object.assign(this.model, row);
     },
      handleClickBatchAdd (){
        if(!this.jEditableParam.jEditableInstance){
          this.jEditableParam.jEditableInstance = this.$refs[this.refKeys[0]];
        }
        this.$refs.jPopupOnlReport.show();
      },
      batchAddPopupCallback(rows){
        if(rows && rows.length > 0){
          let bomDetailTable = this.$refs[this.refKeys[0]];
          let oldData = bomDetailTable.getValuesSync();
          let column = this.mdmBomDetailTable.columns.find(col=>col.key === 'materialDesc')
          let orgFieldsArr = column.orgFields.split(',');
          let destFieldsArr = column.destFields.split(',');
          let addRow, addData
          for(let i =0; i< rows.length; i++){
            if(!(i === 0 && oldData && oldData.values && oldData.values.length===1 && !oldData.values[0].materialDesc)){
              bomDetailTable.add();
            }
            addRow = bomDetailTable.rows[bomDetailTable.rows.length - 1];
            // key转换
            for(let j=0; j<orgFieldsArr.length; j++){
              rows[i][destFieldsArr[j]] = rows[i][orgFieldsArr[j]];
              delete rows[i][orgFieldsArr[j]]
            }
            addData = Object.assign({},rows[i])
            bomDetailTable.popupCallback(addData.material_desc, addData, 'materialDesc'+addRow.id, addRow, column)
          }
        }
      },
      addRowCallback(rowAndTable){
        let id = rowAndTable.row.id
        if(id){
          this.mdmBomDetailAddIdList.push(id);
        }
      },
      checkBomUnique(){

      }
    }
  }
</script>

<style scoped>
  .gap {
    padding-left: 8px;
  }
</style>